package com.itheima.controller;

import com.github.pagehelper.PageInfo;
import com.itheima.controller.Result.Result;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    //添加
    @PostMapping
    public Result save(@RequestBody User user){
        boolean flag = userService.save(user);
        Result result = new Result();
        if (flag == true){
            result.setFlag(true);
        }else {
            result.setFlag(false);
            result.setMessage("保存失败");
        }
        return result;
    }

    //修改
    @PutMapping
    public Result update(@RequestBody User user){
        boolean flag = userService.update(user);
        Result result = new Result();
        if (flag == true){
            result.setFlag(true);
        }else {
            result.setFlag(false);
            result.setMessage("修改失败");
        }
        return result;
    }

    //删除
    @DeleteMapping("/{uuid}")
    public Result delete(@PathVariable int uuid){
        boolean flag = userService.delete(uuid);
        Result result = new Result();
        if (flag == true){
            result.setFlag(true);
        }else {
            result.setFlag(false);
            result.setMessage("删除失败");
        }
        return result;
    }

    //根据id进行查询
    @GetMapping("/{uuid}")
    public Result get(@PathVariable int uuid){
        User user = userService.get(uuid);
        Result result = new Result();
        if (user != null){
            result.setFlag(true);
            result.setData(user);
        }else {
            result.setFlag(false);
            result.setMessage("根据id查询失败");
        }
        return result;
    }

    //分页查询
    @GetMapping()
    public Result getAll(int page,int pagesize){
        PageInfo<User> all = userService.getAll(page, pagesize);
        Result result = new Result();
        if (all != null){
            result.setFlag(true);
            result.setData(all);
        }else {
            result.setFlag(false);
            result.setMessage("分页查询失败");
        }
        return result;
    }


    @PostMapping("/login")
    public Result login(@RequestBody User user){
        User login = userService.login(user.getUserName(), user.getPassword());
        Result result = new Result();
        if (login != null){
            result.setFlag(true);
            result.setData(login);
        }else {
            result.setFlag(false);
            result.setMessage("登录失败");
        }
        return result;
    }



}
